<?php

namespace app\extra\Duiba;

use think\Config;
use app\common\business\user\Point as PointBn;
use app\common\business\log\Duiba as DuibaBn;

class Duiba {

    public $_AppKey;
    public $_AppSecret;

    public function __construct() {
        $this->_AppKey = Config('app.duiba.AppKey');
        $this->_AppSecret = Config('app.duiba.AppSecret');

    }
    /*
    *  md5签名，$array中务必包含 appSecret
    */
    public function sign($array){
        ksort($array);
        $string="";
        while (list($key, $val) = each($array)){
            $string = $string . $val ;
        }
        return md5($string);
    }
    /*
    *  签名验证,通过签名验证的才能认为是合法的请求
    */
    public function signVerify($appSecret,$array){
        $newarray=array();
        $newarray["appSecret"]=$appSecret;
        reset($array);
        while(list($key,$val) = each($array)){
            if($key != "sign" ){
                $newarray[$key]=$val;
            }

        }
        $sign=$this->sign($newarray);
        if($sign == $array["sign"]){
            return true;
        }
        return false;
    }

    /*
*构建参数请求的URL
*/
    public function AssembleUrl($url, $array)
    {
        unset($array['appSecret']);
        foreach ($array as $key=>$value) {
            $url=$url.$key."=".urlencode($value)."&";
        }
        return $url;
    }

    /*
    *  生成自动登录地址
    *  通过此方法生成的地址，可以让用户免登录，进入积分兑换商城
    */
    public function buildCreditAutoLoginRequest($uid,$credits){
        $url = "http://www.duiba.com.cn/autoLogin/autologin?";
        $timestamp=time()*1000 . "";
        $array=array("uid"=>$uid,"credits"=>$credits,"appSecret"=>$this->_AppSecret,"appKey"=>$this->_AppKey,"timestamp"=>$timestamp);
        $sign=$this->sign($array);
        $array['sign']=$sign;
        $url=AssembleUrl($url,$array);
        return $url;
    }

    /*
    *  生成直达商城内部页面的免登录地址
    *  通过此方法生成的免登陆地址，可以通过redirect参数，跳转到积分商城任意页面
    */
    public function buildRedirectAutoLoginRequest($uid,$redirect){
        $credits= PointBn::mypoint($uid);
        $url = "http://www.duiba.com.cn/autoLogin/autologin?";
        $timestamp=time()*1000 . "";
        $array=array("uid"=>$uid,"credits"=>$credits,"appSecret"=>$this->_AppSecret,"appKey"=>$this->_AppKey,"timestamp"=>$timestamp);
        if($redirect!=null){
            $array['redirect']=$redirect;
        }
        $sign=$this->sign($array);
        $array['sign']=$sign;
        $url=$this->AssembleUrl($url,$array);
        return $url;
    }

    /*
    *  积分消耗请求的解析方法
    *  当用户进行兑换时，兑吧会发起积分扣除请求，开发者收到请求后，可以通过此方法进行签名验证与解析，然后返回相应的格式
    *  返回格式为：
    *  成功：{"status":"ok", 'errorMessage':'', 'bizId': '20140730192133033', 'credits': '100'}
    *  失败：{'status': 'fail','errorMessage': '失败原因（显示给用户）','credits': '100'}
    */
    public function parseCreditConsume($request_array){
        if($request_array["appKey"] != $this->_AppKey){
            exception("appKey not match", 102);
        }
        if($request_array["timestamp"] == null ){
            exception("timestamp can't be null", 103);
        }
        $verify=$this->signVerify($this->_AppSecret,$request_array);
        if(!$verify){
            exception("sign verify fail", 104);
        }
        $update=array();
        $update['orderNum']=$request_array['orderNum'];
        $update['description']=$request_array['description'];
        $update['type']=$request_array['type'];
        $update['user_id']=$request_array['uid'];
        $update['credits']=$request_array['credits'];

        $update['change_type']=2;
        $update['change_memo']='商店兑换积分';
        $ret=DuibaBn::insertDuibaLog($update);
        $ret=array( "credits"=>$ret, "description"=>$request_array["description"],"orderNum"=>$request_array["orderNum"]);
        return $ret;
    }

    /*
    *  兑换订单的结果通知请求的解析方法
    *  当兑换订单成功时，兑吧会发送请求通知开发者，兑换订单的结果为成功或者失败，如果为失败，开发者需要将积分返还给用户
    */
    public function  parseCreditNotify($request_array){
        if($request_array["appKey"] != $this->_AppKey){
            exception("appKey not match", 102);
        }
        if($request_array["timestamp"] == null ){
            exception("timestamp can't be null", 103);
        }
        $verify=$this->signVerify($this->_AppSecret,$request_array);
        if(!$verify){
            exception("sign verify fail", 104);
        }

        if($request_array["success"]=='false'){
            $where['bizId']  = $request_array['bizId'];
            $where['status'] = 1;
            DuibaBn::duibaInfo($where);
        }
        return 'ok';
    }

}
